/*
    Copyright (C) 2008-2009 Dmitry Gusev <dmitry.gusev@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

package dmitrygusev.web4konverta.mobile;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

/**
 *
 * @author dmitrygusev
 */
public class Controller {
    
    private static final Controller instance = new Controller();

    private static final ApplicationState as = ApplicationState.getInstance();
    
    private Controller() {
    }

    public static Controller getInstance() {
        return instance;
    }

    public String obtainCookie() throws IOException, Exception {
        HttpConnection conn = null;
        
        try
        {
            conn = (HttpConnection) Connector.open(
                    "http://www.4konverta.com/login/process");

            String msg = "login=" + Utils.encode(as.getAppConfig().getAccountName()) + 
                     "&password=" + Utils.encode(as.getAppConfig().getAccountPassword());

            conn.setRequestMethod(HttpConnection.POST);
            
            conn.setRequestProperty("Content-Length", "" + msg.length());
            conn.setRequestProperty("Content-Type", 
                    "application/x-www-form-urlencoded");

            OutputStream os = conn.openOutputStream();

            os.write(msg.getBytes());

            int rc = conn.getResponseCode();

            if (rc != 302) {
                if (rc == 200)
                {
                    throw new LoginException("Неверные логин/пароль");
                }
                else
                {
                    throw new Exception(
                            "Ошибка 4k-m-001: HTTP 302 expected but was " + rc);
                }
            }

            return conn.getHeaderField("Set-Cookie");
        } finally {
            if (conn != null)
            {
                try { conn.close(); } catch (IOException e) {}
                conn = null;
            }
        }
    }
    
    public EnvelopeController grabEnvelope(Date today) throws IOException {
       String envelopeURL = Utils.buildEnvelopeURL(today);

       String html = Utils.readEnvelopeHtml(envelopeURL, as.getCookie());

       return new EnvelopeController(
               html, envelopeURL, Utils.getMonday(today), Utils.getSunday(today));
    }
}
